//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the 
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003. 
//
//All Rights Reserved.

package org.columba.mail.gui.config.columns;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.columba.core.gui.base.ButtonWithMnemonic;
import org.columba.core.gui.base.SingleSideEtchedBorder;
import org.columba.core.gui.util.DialogHeaderPanel;
import org.columba.core.help.HelpManager;
import org.columba.core.xml.XmlElement;
import org.columba.mail.command.IMailFolderCommandReference;
import org.columba.mail.folder.IMailbox;
import org.columba.mail.folderoptions.ColumnOptionsPlugin;
import org.columba.mail.folderoptions.FolderOptionsController;
import org.columba.mail.gui.frame.MailFrameMediator;
import org.columba.mail.util.MailResourceLoader;
import org.frapuccino.checkablelist.CheckableItemImpl;
import org.frapuccino.checkablelist.CheckableItemListTableModel;
import org.frapuccino.checkablelist.CheckableList;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * Configurabe visible columns of the table.
 * <p>
 * TODO (@author fdietz): adding of columns is not working currently
 * 
 * @author fdietz
 */

public class ColumnConfigDialog extends JDialog implements ActionListener,
		ListSelectionListener {

	private JButton showButton;

	private JButton hideButton;

	private CheckableList list;

	private int index;

	private XmlElement columns;

	private CheckableItemImpl selection;

	private MailFrameMediator mediator;

	public ColumnConfigDialog(MailFrameMediator mediator, XmlElement columns) {
		super((JFrame) mediator.getView().getFrame(), MailResourceLoader
				.getString("dialog", "columns", "title"), true);
		this.mediator = mediator;
		this.columns = columns;

		list = new CheckableList();
		list.getSelectionModel().addListSelectionListener(this);

		initComponents();
		updateComponents(true);

		getRootPane().registerKeyboardAction(this, "CLOSE",
				KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
				JComponent.WHEN_IN_FOCUSED_WINDOW);
		pack();
		setLocationRelativeTo(null);
		setVisible(true);
	}

	protected JPanel createButtonPanel() {
		JPanel bottom = new JPanel();
		bottom.setLayout(new BorderLayout());

		bottom.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));

		ButtonWithMnemonic cancelButton = new ButtonWithMnemonic(
				MailResourceLoader.getString("global", "cancel"));

		//$NON-NLS-1$ //$NON-NLS-2$
		cancelButton.addActionListener(this);
		cancelButton.setActionCommand("CANCEL"); //$NON-NLS-1$

		ButtonWithMnemonic okButton = new ButtonWithMnemonic(MailResourceLoader
				.getString("global", "ok"));

		//$NON-NLS-1$ //$NON-NLS-2$
		okButton.addActionListener(this);
		okButton.setActionCommand("OK"); //$NON-NLS-1$
		okButton.setDefaultCapable(true);
		getRootPane().setDefaultButton(okButton);

		ButtonWithMnemonic helpButton = new ButtonWithMnemonic(
				MailResourceLoader.getString("global", "help"));

		// associate with JavaHelp
		HelpManager.getInstance().enableHelpOnButton(helpButton,
				"configuring_columba");
		HelpManager.getInstance().enableHelpKey(getRootPane(),
				"configuring_columba");

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new GridLayout(1, 3, 6, 0));
		buttonPanel.add(okButton);
		buttonPanel.add(cancelButton);
		buttonPanel.add(helpButton);

		bottom.add(buttonPanel, BorderLayout.EAST);
		return bottom;
	}

	public void initComponents() {

		showButton = new ButtonWithMnemonic(MailResourceLoader.getString(
				"dialog", "columns", "show"));
		showButton.setActionCommand("SHOW");
		showButton.addActionListener(this);
		showButton.setEnabled(false);

		hideButton = new ButtonWithMnemonic(MailResourceLoader.getString(
				"dialog", "columns", "hide"));
		hideButton.setActionCommand("HIDE");
		hideButton.setEnabled(false);
		hideButton.addActionListener(this);

		getContentPane().add(createPanel(), BorderLayout.CENTER);

		getContentPane().add(createBottomPanel(), BorderLayout.SOUTH);

		getContentPane().add(
				new DialogHeaderPanel(MailResourceLoader.getString("dialog",
						"columns", "header_title"), MailResourceLoader
						.getString("dialog", "columns", "header_description")),
				BorderLayout.NORTH);
	}

	private JPanel createPanel() {
		JPanel jpanel1 = new JPanel();
		FormLayout formlayout1 = new FormLayout(
				"FILL:DEFAULT:GROW(1.0),3DLU,FILL:DEFAULT:NONE",
				"CENTER:DEFAULT:NONE,1DLU,FILL:DEFAULT:GROW(1.0),3DLU,CENTER:DEFAULT:NONE");
		CellConstraints cc = new CellConstraints();
		jpanel1.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
		jpanel1.setLayout(formlayout1);

		JLabel jlabel1 = new JLabel();
		jlabel1.setText("Columns:");
		jpanel1.add(jlabel1, cc.xy(1, 1));

		JScrollPane scrollPane = new JScrollPane(list);
		scrollPane.setPreferredSize(new Dimension(250, 200));
		jpanel1.add(scrollPane, cc.xy(1, 3));

		jpanel1.add(createPanel1(), new CellConstraints(3, 3, 1, 1,
				CellConstraints.DEFAULT, CellConstraints.TOP));

		return jpanel1;
	}

	private JPanel createPanel1() {
		JPanel jpanel1 = new JPanel();
		FormLayout formlayout1 = new FormLayout("FILL:DEFAULT:NONE",
				"CENTER:DEFAULT:NONE,3DLU,CENTER:DEFAULT:NONE,3DLU,CENTER:DEFAULT:NONE");
		CellConstraints cc = new CellConstraints();
		jpanel1.setLayout(formlayout1);

		jpanel1.add(showButton, cc.xy(1, 1));

		jpanel1.add(hideButton, cc.xy(1, 3));

		return jpanel1;
	}

	/**
	 * 
	 */
	private JPanel createBottomPanel() {
		JPanel bottomPanel = new JPanel(new BorderLayout());
		bottomPanel.setBorder(new SingleSideEtchedBorder(SwingConstants.TOP));

		JPanel buttonPanel = createButtonPanel();

		bottomPanel.add(buttonPanel, BorderLayout.EAST);

		return bottomPanel;
	}

	private XmlElement findColumn(XmlElement parent, String name) {
		for (int i = 0; i < parent.count(); i++) {
			XmlElement child = parent.getElement(i);
			if (child.getAttribute("name").equals(name)) {
				return child;
			}
		}
		return null;
	}

	public void updateComponents(boolean b) {
		if (b) {
			CheckableItemListTableModel model = new CheckableItemListTableModel();
			String[] stringList = ColumnOptionsPlugin.getColumns();

			for (int j = 0; j < stringList.length; j++) {
				String c = stringList[j];
				CheckableItemImpl item = new CheckableItemImpl(c);
				XmlElement element = findColumn(columns, c);
				item.setSelected(element != null);
				model.addElement(item);
			}

			list.setModel(model);
		} else {
			CheckableItemListTableModel model = ((CheckableItemListTableModel) list
					.getModel());

			for (int i = 0; i < model.count(); i++) {
				// get column of list
				CheckableItemImpl column = (CheckableItemImpl) model
						.getElement(i);

				// find colum
				XmlElement element = findColumn(columns, column.toString());

				if (element != null) {
					// remove disabled column
					if (!column.isSelected()) {
						element.removeFromParent();
					}
				} else {
					if (column.isSelected()) {
						XmlElement newElement = new XmlElement("column");
						newElement.addAttribute("name", column.toString());
						newElement.addAttribute("width", "100");
						columns.addElement(newElement);
					}
				}
			}
		}
	}

	public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting()) {
			return;
		}

		DefaultListSelectionModel theList = (DefaultListSelectionModel) e
				.getSource();
		if (!theList.isSelectionEmpty()) {
			index = theList.getAnchorSelectionIndex();

			selection = (CheckableItemImpl) ((CheckableItemListTableModel) list
					.getModel()).getElement(index);

			updateButtonState();
		}
	}

	private void updateButtonState() {
		if (selection.isSelected()) {
			hideButton.setEnabled(true);
			showButton.setEnabled(false);
		} else {
			showButton.setEnabled(true);
			hideButton.setEnabled(false);
		}
	}

	public void actionPerformed(ActionEvent e) {
		String action = e.getActionCommand();

		if (action.equals("OK")) {
			updateComponents(false);

			setVisible(false);

			ColumnOptionsPlugin plugin = (ColumnOptionsPlugin) ((FolderOptionsController) mediator
					.getFolderOptionsController()).getPlugin("ColumnOptions");

			// make sure this configuration is also visually working immediately
			IMailFolderCommandReference r = mediator.getTreeSelection();
			plugin.loadOptionsFromXml((IMailbox) r.getSourceFolder());
		} else if (action.equals("CANCEL")) {
			setVisible(false);
		} else if (action.equals("SHOW")) {
			if (selection != null) {
				selection.setSelected(!selection.isSelected());
				((CheckableItemListTableModel) list.getModel())
						.updateRow(selection);

				// list.repaint();
				updateButtonState();
			}
		} else if (action.equals("HIDE")) {
			// disable selected item
			if (selection != null) {
				selection.setSelected(!selection.isSelected());
				((CheckableItemListTableModel) list.getModel())
						.updateRow(selection);

				// list.repaint();
				updateButtonState();
			}
		}
	}
}